package sockettest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;

import org.junit.Test;

/**
 * socket测试类
 * @author ZZWang
 * @Time 2017年9月14日  上午9:45:50
 */
public class SocketDemo {

	/**
	 * 测试InetAddress
	 * @throws UnknownHostException
	 */
	@Test
	public void testInetAddress() throws UnknownHostException {
		InetAddress address = InetAddress.getByName("115.159.159.109");
		String hostAddress = address.getHostAddress(); // 获取ip地址
		String hostName = address.getHostName(); // 获取计算机名
		byte[] address2 = address.getAddress(); // 获取字节数组形式的ip地址
		InetAddress localAddress = InetAddress.getByName("127.0.0.1");
		String hostName2 = localAddress.getHostName();

	}

	@Test
	public void testURL() throws MalformedURLException {
		URL baidu = new URL("http://baidu.com");
		URL url = new URL(baidu, "/index.html?username=tom#test");
		String protocol = url.getProtocol();
		String host = url.getHost();
		int port = url.getPort();
		String query = url.getQuery();
		String path = url.getPath();
	}

	@Test
	public void testPage() throws IOException {
		URL baiduUrl = new URL("http://neihanshequ.com/");
		InputStream baiduInput = baiduUrl.openStream();
		InputStreamReader reader = new InputStreamReader(baiduInput, "utf-8");
		BufferedReader bufferRea = new BufferedReader(reader);
		String data;
		while ((data = bufferRea.readLine()) != null) {
			System.out.println(data);
		}
		bufferRea.close();
		reader.close();
		baiduInput.close();
	}

	@Test
	public void testSocket() throws IOException {
		ServerSocket serverSocket = new ServerSocket(8080);
		Socket socket = serverSocket.accept();
		InputStream input = socket.getInputStream();
		InputStreamReader reader = new InputStreamReader(input, "utf-8");
		BufferedReader bufferRea = new BufferedReader(reader);
		String data;
		while ((data = bufferRea.readLine()) != null) {
			System.out.println("我是服务器，客户端说：" + data);
		}
		// 关闭输入流
		socket.shutdownInput();
		OutputStream output = socket.getOutputStream();
		OutputStreamWriter writer = new OutputStreamWriter(output,"utf-8");
		BufferedWriter bufferWri = new BufferedWriter(writer);
		bufferWri.write("欢迎您！");
		
		bufferWri.close();
		writer.close();
		output.close();
		bufferRea.close();
		reader.close();
		input.close();
		socket.close();
		serverSocket.close();
	}

}
